from typing import List, Optional, Dict, Any
from sqlalchemy.orm import Session

from models.Notification import Notification
from schemas.Notification import NotificationCreate, NotificationUpdate

class NotificationService:
    """
    通知服务类，提供通知相关的业务逻辑
    """
    
    def get_by_id(self, db: Session, id: int) -> Optional[Notification]:
        """
        根据 ID 获取通知
        """
        return db.query(Notification).filter(Notification.id == id, Notification.isDelete == False).first()
    
    def get_all(self, db: Session, skip: int = 0, limit: int = 100) -> List[Notification]:
        """
        获取所有未删除的通知
        """
        return db.query(Notification).filter(Notification.isDelete == False).offset(skip).limit(limit).all()
    
    def get_by_email(self, db: Session, email: str) -> List[Notification]:
        """
        根据邮箱获取通知
        """
        return db.query(Notification).filter(
            Notification.email == email,
            Notification.isDelete == False
        ).all()
    
    def create(self, db: Session, notification: NotificationCreate) -> Notification:
        """
        创建新通知
        """
        db_notification = Notification(
            id=notification.id,
            email=notification.email,
            count=notification.count,
            isDelete=False
        )
        db.add(db_notification)
        db.commit()
        db.refresh(db_notification)
        return db_notification
    
    def update(self, db: Session, notification_id: int, notification_update: NotificationUpdate) -> Optional[Notification]:
        """
        更新通知
        """
        db_notification = db.query(Notification).filter(Notification.id == notification_id).first()
        if db_notification is None:
            return None
        
        # 更新字段
        update_data = notification_update.dict(exclude_unset=True)
        for key, value in update_data.items():
            setattr(db_notification, key, value)
        
        db.commit()
        db.refresh(db_notification)
        return db_notification
    
    def delete(self, db: Session, notification_id: int) -> bool:
        """
        软删除通知
        """
        db_notification = db.query(Notification).filter(Notification.id == notification_id).first()
        if db_notification is None:
            return False
        
        db_notification.isDelete = True
        db.commit()
        return True
    
    def check_id_exists(self, db: Session, id: int) -> bool:
        """
        检查 ID 是否已存在
        """
        return db.query(Notification).filter(Notification.id == id).first() is not None